from django.shortcuts import render
from .forms import UploadFileForm
from django.http import HttpResponseRedirect
from aip import AipImageSearch
import json
from django.conf import settings
import os

APP_ID = '11595466'
API_KEY = '3ueGbMyY3RMVoGIHZixlgGe8'
SECRET_KEY = 'f2kFd0ByF7IT0bHjU5nRNC1LSrcbNN9x'
client = AipImageSearch(APP_ID, API_KEY, SECRET_KEY)

cats = {'T恤': 1,
        '休闲裤': 2,
        '牛仔裤': 3,
        '衬衫': 4,
        '夹克': 5,
        '马甲/背心': 6,
        '针织衫': 7,
        '卫衣': 8,
        '短裤': 9,
        'POLO衫': 10,
        '风衣': 11,
        '西裤': 12,
        '西服': 13,
        '毛呢大衣': 14,
        '仿皮皮衣': 15,
        '羽绒服': 16,
        '羊毛衫': 17,
        '真皮皮衣': 18,
        '棉服': 19,
        '西服套装': 20,
        '卫裤/运动裤': 21}

# Create your views here.
def index(request):
    # Handle file upload
    images = []
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            cat = form.cleaned_data['cate']
            images = handle_uploaded_file(request.FILES['file'], pn='0', rn='100', class_id1=cat)
            # return HttpResponseRedirect('index')

    else:
        form = UploadFileForm()  # A empty, unbound form

    # Render list page with the documents and the form
    return render(
        request,
        'core/index.html',
        {'images': images, 'form': form}
    )


def handle_uploaded_file(f, **kwargs):
    result = []
    data = client.productSearch(f.read(), options=kwargs)['result']
    for item in data:
        result.append({'score': item['score'], 'image': json.loads(item['brief'])['图片']})

    save_path = os.path.join(os.path.join(settings.BASE_DIR, "uploads"), 'uploaded_image.jpg')
    with open(save_path, 'wb+') as saved_file:
        for chunk in f.chunks():
            saved_file.write(chunk)

    return result
